package com.dpj.reentranloock_test;

import lombok.extern.slf4j.Slf4j;


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j(topic = "c.ConditionTest")
public class ConditionTest {
    static final Object room = new Object();
    static boolean hasCigarette = false; //有没有烟
    static boolean hasTakeout = false;//外卖到了没
    static ReentrantLock ROOM = new ReentrantLock();
    //等待烟的休息室
    static Condition waitCigaretteSet = ROOM.newCondition();
    //等待外卖的休息室
    static Condition waitTakeOutSet = ROOM.newCondition();

    //解决虚假唤醒，将if换为了while
    public static void main(String[] args) throws InterruptedException {
        new Thread(() -> {
            ROOM.lock();
            try {
                log.debug("有烟没？[{}]", hasCigarette);
                while (!hasCigarette) { //在这里为了防止虚假唤醒，将if换为了while
                    log.debug("没烟,先歇会儿!");
                    try {
                        waitCigaretteSet.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                if (hasCigarette) {
                    log.debug("有烟,可以干活了!");
                }
            }
             finally {
                ROOM.unlock();
            }

        }, "小南").start();

        new Thread(() -> {
            ROOM.lock();
            try {
                log.debug("外卖到了？[{}]", hasTakeout);
                while (!hasTakeout) { // 在这里为了防止虚假唤醒，将if换为了while
                    log.debug("没外卖,先歇会儿!");
                    try {
                        waitTakeOutSet.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                log.debug("外卖到了,可以干活了!");


            } finally {
                ROOM.unlock();
            }

        }, "小女").start();
        Thread.sleep(1000);
        new Thread(() -> {
            ROOM.lock();
            try {
                hasCigarette=true;
                waitCigaretteSet.signal();
            } finally {
                ROOM.unlock();
            }

        }, "送外卖的").start();

        Thread.sleep(1000);
        new Thread(() -> {
            ROOM.lock();
            try {
                hasTakeout=true;
                waitTakeOutSet.signal();
            } finally {
                ROOM.unlock();
            }

        }, "送烟的").start();

    }
}
